package com.lyy.utils;

import ch.qos.logback.core.net.SyslogOutputStream;
import io.jsonwebtoken.*;
import jdk.internal.dynalink.beans.StaticClass;
import jdk.nashorn.internal.ir.ReturnNode;

import java.util.Date;

/**
 * jwt工具类
 */
public class JwtUtils {
    public static void main(String[] args) {
        //createToken("lyy123");
        getUserInfo("");
    }

    public static String createToken(String username){
        try {
            JwtBuilder builder= Jwts.builder()
                    .setId("id")
                    .setSubject("lyy-token")
                    .claim("username",username)
                    .setIssuedAt(new Date())
                    .signWith(SignatureAlgorithm.HS256,"lyy-test")//第2个参数是密钥,长度要大于3
                    .setExpiration(new Date(System.currentTimeMillis()+60*1000));//设置过期时间为1分钟
            //生成token字符串
            return builder.compact();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public static String getUserInfo(String tokenStr){
        try {
            Claims body = Jwts.parser().setSigningKey("lyy-test").parseClaimsJws(tokenStr).getBody();
            Object username = body.get("username");
            System.out.println(username);
            return username.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
}
